/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package czat;

import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.util.NoSuchElementException;
import java.util.Scanner;

/**

 @author zztbak01
 */
public class WatekSerweraDlaKlienta extends Thread {

	SerwerCzatu server;
	Socket socket;
	OutputStream os;
	Scanner is;
	String login;

	public WatekSerweraDlaKlienta(Socket socket, SerwerCzatu server) throws IOException {
		this.socket = socket;
		this.server = server;
		os = socket.getOutputStream();
		is = new Scanner(socket.getInputStream());
		login = is.nextLine();
		this.start();
	}

	public void wyslij(String text) {
		try {
			os.write((text + "\n").getBytes());
		} catch (IOException ex) {
			server.clientDisconnected(login);
		}
	}

	public void parseText(String text) {
		if (text.startsWith("LOGOUT")) {
			try {
				wyslij("zamknieto połączenie");
				os.close();
				is.close();
				socket.close();
			} catch (Exception ignoreMe) {
			}
			throw new NoSuchElementException();
		}
		if (text.startsWith("TEXT")) {
			String[] napisy = text.split(";", 3);
			server.send(login, napisy[1], napisy[2], "TEXT");
		}
	}

	@Override
	public void run() {
		String line;
		while (true) {
			try {
				line = is.nextLine();
				parseText(line);
				System.out.println(login + ": " + line + "\n");
			} catch (NoSuchElementException ex) {
				server.clientDisconnected(login);
				break;
			}
		}
	}
}
